# coding: utf-8

import re
import copy
import json
from uuid import uuid4

from django.core.paginator import Paginator
from django.core.paginator import PageNotAnInteger
from django.core.paginator import EmptyPage


from jobs.models import TaskInputParams, TaskConf

class DDPagination(object):
    '''
        {
            'page': 当前第几页,
            'total': 一共多少项
            'size': 一页多少个
            result: 返回时的实例对象
        }
    '''
    page_size = 10
    page_kwarg = 'page'
    page_size_kwarg = 'size'

    def __init__(self, request, queryset):
        self.request = request
        self.paginator = Paginator(queryset, self.size)
        print self.size

    def pagination(self):
        return {'page': self.page, 'size': self.size, 'total': self.total, 'result': self.result}

    @property
    def result(self):
        try:
            page = self.paginator.page(self.page)
        except PageNotAnInteger:
            page = self.paginator.page(1)
        except EmptyPage:
            page = self.paginator.page(self.paginator.num_pages)
        return page.object_list

    @property
    def total(self):
        return self.paginator.count

    @property
    def page(self):
        return self.request.GET.get(self.page_kwarg, 1)

    @property
    def size(self):
        return self.request.GET.get(self.page_size_kwarg, self.page_size)


def search_filed(data):
    field_dict = {
        'name': {'pattern': re.compile('name'), 'name': 'name'},
        'desc': {'pattern': re.compile('desc'), 'name': 'desc'},
        'type': {'pattern': re.compile('type'), 'name': 'type'},
        'default': {'pattern': re.compile('default'), 'name': 'default'},
        'required': {'pattern': re.compile('required'), 'name': 'required'},
    }
    index_pattern = re.compile('\d+')
    for field, action in field_dict.items():
        if not action['pattern'].search(data):
            continue
        index_search = index_pattern.search(data)
        if index_search:
            return field, index_search.group()[0]
    return None, None


class VarDict(dict):

    def __setitem__(self, key, value):
        if key == 'required':
            value = True
        return super(VarDict, self).__setitem__(key, value)


def str2int(value):
    try:
        return int(value)
    except:
        return False


class TaskRunValidate(object):

    def __init__(self, request, task):
        self.task = task
        self.data = copy.deepcopy(request.POST)
        self.request = request
        self.task_conf = TaskConf.objects.filter(task_id=task.id).first()
        self.task_params = [task for task in TaskInputParams.objects.filter(task_id=task.id).all()]

    def is_validate(self):
        if self.validate_input() and self.validate_conf() and self.validate_user():
            return True
        return False

    def validate_input(self):
        for param in self.task_params:
            if param.required:
                value = self.data.get(param.name, None)
                if not value:
                    print 'no field', param.name
                    return False
            if param.type == 'int' and not str2int(value):
                print 'to int fialed', value
                return False
        return True

    def validate_user(self):
        user = self.data.get('run_user', None)
        if not user:
            print 'no run user'
            return False
        print user
        try:
            user_list = self.task_conf.user_list.split(',')
        except:
            user_list = []
        if user_list:
            if self.task_conf.user_action == 'allow':
                if user in user_list:
                    return True
                return False
            else:
                if user in user_list:
                    return False
                return True
        return True

    def validate_conf(self):
        if not self.task_conf.timeout or not str2int(self.task_conf.timeout):
            print 'not timeout'
            return False
        if not self.data.get('hosts', []):
            return False
        return True

    def json_data(self):
        if self.data.get('csrfmiddlewaretoken', None):
            self.data.pop('csrfmiddlewaretoken')
        return json.dumps(self.data)

    def hosts(self):
        return [host for host in self.data['hosts'].split(',')]

    def hosts_string(self):
        return self.data['hosts']

    @property
    def model_data(self):
        return {
            'params': self.json_data(), 'task_id': self.task.id,'hosts': self.hosts_string(),
            'status': 'QUEUE', 'celery_task_id': '{}'.format(uuid4()),
            'create_user': self.request.user.username,  'desc': self.data.get('desc', '')
        }
